package com.lx.bizimpl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lx.biz.IUser;
import com.lx.domain.Tree;
import com.lx.domain.AdminUser;

@Transactional
@Service("iUserimpl")
public class IUserimpl implements IUser {

	@Autowired
	private SessionFactory sessionFactory;  

	public void setSessionFactory(SessionFactory sessionFactory) {  
	    this.sessionFactory = sessionFactory;  
	}  
	
	@Override
	public AdminUser findUser(String username, String password) {
		String hql = "FROM AdminUser WHERE username = ?" ;
		Query query = sessionFactory.getCurrentSession().createQuery(hql) ;
		query.setString(0, username);
		AdminUser user =(AdminUser)query.uniqueResult();
		if (user.getPassword().equals(password)) {
			return user ;
		}else {
			return null ;
		}
		
	}

	@Override
	public int checkUser(String username){
		String hql = "FROM AdminUser WHERE username = ? " ;
		Session session = sessionFactory.getCurrentSession();
		Query query =session.createQuery(hql);
		query.setString(0, username);
		AdminUser user =(AdminUser)query.uniqueResult();
		int result = 0 ;
		if (!(user ==null)) {
			result =1 ;
		}
		return result ;
	}

	
	@Override
	public List<AdminUser> listUser() {
		String hqlString ="FROM AdminUser" ;
		Query query =sessionFactory.getCurrentSession().createQuery(hqlString);
		
		return query.list();
	}

	@Override
	public int countUser() {
		String hqlString = "SELECT count(*) FROM AdminUser" ;
		Query query= sessionFactory.getCurrentSession().createQuery(hqlString);
		Number count = (Number)query.list().get(0);
 		return count.intValue();
	}

	@Override
	public List<AdminUser> listUser(String rows, String page, String sort,
			String order, String name, String date_from, String date_to) {
		String hql = "FROM AdminUser " ;
		String hql2 ="";
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Integer first = Integer.parseInt(rows) * (Integer.parseInt(page)-1);
		
		if (name !=null && !name.equals("")) {
			hql2 += "username like :name AND " ;
			
		}
		if (date_from !=null && !date_from.equals("")) {
			hql2 += "creatTime >= :date_from  AND ";
			
		}
		if (date_to !=null && !date_to.equals("")) {
			hql2 += "creatTime <= :date_to AND ";
			
		}
		if (!hql2.equals("")) {
			hql2 = "WHERE " + hql2.substring(0,hql2.length()-4);
		}
		
		hql += hql2 + " ORDER BY "+ sort +" " +order + "";
	  	Query query =sessionFactory.getCurrentSession().createQuery(hql);
		if (name !=null && !name.equals("")) {
			query.setParameter("name", "%"+name+"%") ;
		
		}
		if (date_to !=null && !date_to.equals("")) {
			try {
				Date dateto = dateFormat.parse(date_to);
				query .setDate("date_to",dateto) ;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		if (date_from !=null && !date_from.equals("")) {
			try {
				Date datefrom = dateFormat.parse(date_from);
				query.setDate("date_from",datefrom) ;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		  query.setFirstResult(first) ;
		  query.setMaxResults((Integer.parseInt(rows))) ;
		 /*  query.setParameter("pageSize", (Integer.parseInt(rows)));
		   query.setParameter("first", first);
		   */
		   
		
		return query.list();
	}

	@Override
	public int countUser(String rows, String page, String sort, String order,
			String name, String date_from, String date_to) {
		String hql = "SELECT count(*) FROM AdminUser " ;
		String hql2 ="";
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		if (name !=null && !name.equals("")) {
			hql2 += "username like :name AND " ;
			
		}
		if (date_from !=null && !date_from.equals("")) {
			hql2 += "creatTime >= :date_from  AND ";
			
		}
		if (date_to !=null && !date_to.equals("")) {
			hql2 += "creatTime <= :date_to AND ";
			
		}
		if (!hql2.equals("")) {
			hql2 = "WHERE " + hql2.substring(0,hql2.length()-4);
		}
		
		hql += hql2 ;
	  	Query query =sessionFactory.getCurrentSession().createQuery(hql);
		if (name !=null && !name.equals("")) {
			query.setParameter("name", "%"+name+"%") ;
		
		}
		if (date_to !=null && !date_to.equals("")) {
			try {
				Date dateto = dateFormat.parse(date_to);
				query .setDate("date_to",dateto) ;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		if (date_from !=null && !date_from.equals("")) {
			try {
				Date datefrom = dateFormat.parse(date_from);
				query.setDate("date_from",datefrom) ;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		Number count = (Number)query.list().get(0);
 		return count.intValue();
	}

	@Override
	public String saveOrUpdateUser(AdminUser user,String creatTime1) {
		Date creatTime;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
		String result =null ;
		if (user.getId()!=null&&user.getId()!=0) {
			
				/*creatTime = sdf.parse(creatTime1) ;*/
				String hqlString = "FROM AdminUser Where id <> ? and username = ?" ;
				String hql2 = "FROM AdminUser Where id = ? " ;
				Query query = sessionFactory.getCurrentSession().createQuery(hqlString) ;
				Query query2 = sessionFactory.getCurrentSession().createQuery(hql2) ;
				query.setInteger(0, user.getId());
				query.setString(1, user.getUsername()) ;
				query2.setInteger(0, user.getId()) ;
				List<AdminUser> list = query.list();
				AdminUser user2 = (AdminUser)query2.uniqueResult() ;
				//用户名重复检查
				if (list.size()>0) { 
					result = "repeat" ;
				}else {
					user2.setIsForbidden(user.getIsForbidden());
					user2.setUsername(user.getUsername());
					user2.setRole(user.getRole());
					sessionFactory.getCurrentSession().saveOrUpdate(user2);
					result = "success" ;
				}
			
		}else {
			
				String hqlString = "FROM AdminUser Where username = ?" ;
				Query query = sessionFactory.getCurrentSession().createQuery(hqlString) ;
				query.setString(0, user.getUsername()) ;
				List<AdminUser> list = query .list() ;
				if (list.size()> 0) {
					result = "repeat" ;
				}else {
					creatTime = new Date() ;
			    	user.setCreatTime(creatTime);
			    	user.setPassword(user.getUsername());
			    	sessionFactory.getCurrentSession().saveOrUpdate(user);
			    	result = "success";
				}
		    	
			
		}
		
		return result ;
		
		
		
		
		
		/*String hql = "FROM User where username = ?" ;
		Query query =sessionFactory.getCurrentSession().createQuery(hql) ;
		query.setString(0, user.getUsername());
		List<User> list = query.list();
		if (list.size() > 0) {
			return "用户名已存在" ;
		}else {
			sessionFactory.getCurrentSession().saveOrUpdate(user);
			return "操作成功" ;
			
		}*/
 		
	}

	@Override
	public List<Tree> list_tree(String id) {
		if (id!=null &&!id.equals("")) {
			String hqlString = "FROM Tree WHERE nid = ?" ;
			Query query = sessionFactory.getCurrentSession().createQuery(hqlString);
			query.setInteger(0, Integer.parseInt(id)) ;
			return query .list() ;
		}else {
			String hqlString = "FROM Tree WHERE nid = ?" ;
			Query query = sessionFactory.getCurrentSession().createQuery(hqlString);
			query.setInteger(0, 0) ;
			return query .list() ;
		}
		
	}

	@Override
	public int deleteUser(String ids) {
		//批量删除方法
		Session session= sessionFactory.getCurrentSession();
		String hql = "DELETE from AdminUser u WHERE ";
		String[] str =ids.split(",");
		for (int i = 0; i < str.length; i++) {
			 if (i==0) {
			//前端传过来的为string类型 先转型 此处用hql连接方式组合
			hql= hql +"id =" +Integer.parseInt(str[i]);
			}else {
			hql =hql +"or id =" +Integer.parseInt(str[i]);
				}
			}
			session.createQuery(hql).executeUpdate();

		
		return str.length;
	}
	
	
}
